﻿// Copyright (c) egmkang wang. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace XServer.SDK.Net
{
    using System;
    using System.Net;
    using System.IO;
    using DotNetty.Buffers;
    using DotNetty.Transport.Channels;
    using XServer.Message;

    public static partial class Ext
    {
        public static IByteBuffer SliceAndRetain(this IByteBuffer buffer, Int32 size)
        {
            IByteBuffer slice = buffer.ReadSlice(size);
            slice.Retain();
            return slice;
        }

        public static Int64 GetSessionID(this IChannel channel)
        {
            var value = channel.GetAttribute(Server.SESSION_ID);
            return value != null ? value.Get().Value : 0;
        }
        public static string GetOpenID(this IChannel channel)
        {
            var value = channel.GetAttribute(Server.OPEN_ID);
            return value != null ? value.Get() : null;
        }
        public static Int64 GetPlayerID(this IChannel channel)
        {
            var value = channel.GetAttribute(Server.PLAYER_ID);
            return value != null ? value.Get().Value : 0;
        }
        public static long GetServerID(this IChannel channel)
        {
            var value = channel.GetAttribute(Server.SERVER_ID);
            return value != null ? value.Get().Value : 0;
        }
        public static IPEndPoint GetIpAddr(this IChannel channel)
        {
            var value = channel.GetAttribute(Server.IP_ADDR);
            return value != null ? value.Get() : null;
        }
        public static Int64 GetActiveTime(this IChannel channel)
        {
            var value = channel.GetAttribute(Server.ACTIVE_TIME);
            return value != null ? value.Get().Value : 0;
        }

        public static ushort GetMsgID(this IMessage msg) => Codec.GetMessageID(msg.GetType().ToString());

        //4字节长度(里面写着N)
        //2字节消息ID
        //N字节消息体
        public static byte[] ToBytes(this IMessage msg)
        {
            //默认2M的包大小
            const int MaxLength = 2 * 1024 * 1024;

            var msgid = msg.GetMsgID();
            var buffer = PooledByteBufferAllocator.Default.Buffer(MaxLength).WithOrder(ByteOrder.LittleEndian);
            int writerIndex = buffer.WriterIndex;
            buffer.WriteInt(0);         //包的长度
            buffer.WriteShort(msgid);   //消息ID

            MemoryStream stream = new MemoryStream(buffer.Array, buffer.WriterIndex + buffer.ArrayOffset, MaxLength);
            msg.Serialize(stream);
            stream.Flush();

            int bodyLength = (int)stream.Position;
            buffer.SetWriterIndex(writerIndex);
            buffer.WriteInt(bodyLength);
            buffer.SetWriterIndex(bodyLength + Constant.MIN_CS_HEAD_LEN);

            var ret = buffer.ReadBytes(buffer.ReadableBytes).ToArray();
            buffer.Release();
            return ret;
        }
    }
}
